<script setup lang="ts">
import { getSourceNameApi, postRetrieveApi } from '@/api/study/course';
import { useSelectedSourceStore } from '@/stores/selectedSourceStore';
import { CopyOutlined, CustomerServiceOutlined } from '@ant-design/icons-vue';
import { message as useMessage } from 'ant-design-vue';
import { reactive, ref } from 'vue';
import useClipboard from 'vue-clipboard3';
import { useRouter } from 'vue-router';

const props = defineProps({
  courseId: {
    type: String,
    required: true,
  },
  folderId: {
    type: String,
    required: true,
  },
  sourceId: {
    type: String,
    required: true,
  },
  filePath: {
    type: String,
    required: true,
  },
});

const { toClipboard } = useClipboard();

const isOpen = ref(false);
const position = reactive({ x: window.innerWidth - 500, y: 50 });
const isGenerating = ref(false);
const inputValue = ref('');
const inputElementRef = ref<HTMLTextAreaElement | null>(null);
const messages = ref<{
  content: string;
  references: string[];
  sender: string;
  recommendedQuestions?: string[];
  referenceDetails?: { id: string; name: string }[];
}[]>([
  {
    content: '您好！我是AI助手小链。您可以询问我任何关于大数据技术的问题。例如，您可以点击下面的推荐问题进行尝试：',
    references: [],
    sender: 'AI',
    recommendedQuestions: [
      '什么是大模型？',
      '什么智能体Agent？',
      '怎么开始入门智能体应用开发？',
    ],
  },
]);

const router = useRouter();

const handleIconClick = () => {
  isOpen.value = true;
};

const handleCloseClick = () => {
  isOpen.value = false;
};

const autoResizeTextarea = () => {
  if (inputElementRef.value) {
    inputElementRef.value.style.height = 'auto';
    inputElementRef.value.style.height = `${inputElementRef.value.scrollHeight}px`;
  }
};

const fetchSourceName = async (sourceId: string): Promise<{ name: string; type: string } | null> => {
  try {
    const response: any = await getSourceNameApi(sourceId);
    return { name: response.data, type: response.msg };
  }
  catch (error) {
    console.error('Request failed:', error);
    return null;
  }
};

const handleSendClick = async () => {
  if (inputValue.value.trim()) {
    const userMessage = { content: inputValue.value, references: [], sender: 'me' };
    messages.value.push(userMessage);
    inputValue.value = '';
    isGenerating.value = true;

    if (inputElementRef.value)
      inputElementRef.value.style.height = 'auto';

    const courseFilePath = props.filePath;

    const cleanQuery = userMessage.content.replace(/^"(.*)"$/, '$1');
    try {
      const response = await postRetrieveApi(cleanQuery, courseFilePath);
      const data = await response;

      const aiMessage = {
        content: data.答案,
        references: Array.isArray(data.参考来源) ? data.参考来源 : [data.参考来源],
        sender: 'AI',
      };

      const referenceDetails = await Promise.all(
        aiMessage.references.map(async (sourceId: string) => {
          const Response = await fetchSourceName(sourceId);
          const nameResponse = Response?.name;
          return { id: sourceId, name: nameResponse || sourceId };
        }),
      );

      messages.value.push({ ...aiMessage, referenceDetails });
    }
    catch (error) {
      console.error('Request failed:', error);
    }
    finally {
      isGenerating.value = false;
    }
  }
};

const handleReferenceClick = async (referenceId: string) => {
  const sourceInfo = await fetchSourceName(referenceId);
  if (sourceInfo) {
    useSelectedSourceStore().setSelectedSourceId(referenceId);
    if (sourceInfo.type === '视频资源') {
      router.push({
        name: 'video',
        params: {
          courseId: props.courseId,
          folderId: props.folderId,
          sourceId: referenceId,
          filePath: props.filePath,
        },
      });
    }
    else if (sourceInfo.type === '文档资源') {
      router.push({
        name: 'DocumentViewer',
        params: {
          courseId: props.courseId,
          folderId: props.folderId,
          sourceId: referenceId,
          filePath: props.filePath,
        },
      });
    }
  }
};

const handleRecommendedQuestionClick = (question: string) => {
  inputValue.value = question;
  autoResizeTextarea();
};
const handleCopyClick = async (text: string) => {
  try {
    await toClipboard(text);
    useMessage.success('复制成功');
  }
  catch (error) {
    useMessage.error('复制失败');
    console.error('复制失败:', error);
  }
};

const startClientX = ref(0); // 记录开始的横坐标位置
const startClientY = ref(0); // 记录开始的纵坐标位置

// 拖拽开始事件
const dragstart = (e: any) => {
  // 记录拖拽元素初始位置
  startClientX.value = e.clientX;
  startClientY.value = e.clientY;
};

// 拖拽完成事件
const dragend = (e: any) => {
  const x = startClientX.value - e.clientX; // 计算偏移量
  const y = startClientY.value - e.clientY;
  position.x -= x; // 实现拖拽元素随偏移量移动
  position.y -= y;
}
</script>

<template>
  <div
    class="draggableContainer"
    :style="{ left: `${position.x}px`, top: `${position.y}px` }"
    draggable="true"
    @dragstart="dragstart($event)"
    @dragend="dragend($event)"
  >
    <div v-if="!isOpen" class="iconContainer" @click="handleIconClick">
      <img src="@/assets/1.png" alt="AI Assistant" class="aiIcon">
      <span class="iconText">小链</span>
      <CustomerServiceOutlined class="customerServiceIcon iconText" />
    </div>
    <div v-else class="chatContainer">
      <div class="chatHeader">
        <div class="headerContent">
          <img src="@/assets/1.png" alt="AI Assistant" class="aiIcon">
          <span>小链</span>
        </div>
        <button class="closeButton" @click="handleCloseClick">
          ×
        </button>
      </div>
      <div class="chatContent">
        <div class="chatMessages">
          <div
            v-for="(msg, index) in messages"
            :key="index"
            class="messageItem" :class="[msg.sender === 'me' ? 'myMessage' : 'aiMessage']"
            :style="msg.sender === 'me' ? { color: '#fff', backgroundColor: 'rgba(0, 51, 153, 0.5)' } : { color: '#000' }"
          >
            <div class="messageBody" :style="msg.sender === 'me' ? { color: '#fff' } : { color: '#000' }">
              <p :style="msg.sender === 'me' ? { color: '#fff' } : { color: '#000' }">
                {{ msg.content }}
              </p>
              <div v-if="msg.sender === 'AI' && msg.recommendedQuestions" class="recommendedQuestions">
                <button
                  v-for="(question, qIndex) in msg.recommendedQuestions"
                  :key="qIndex"
                  class="recommendedQuestionButton"
                  @click="handleRecommendedQuestionClick(question)"
                >
                  {{ question }}
                </button>
              </div>
            </div>
            <div v-if="msg.sender === 'AI' && Array.isArray(msg.referenceDetails)" class="references">
              <p>来源全部文档：</p>
              <ul>
                <li
                  v-for="(refItem, refIndex) in msg.referenceDetails"
                  :key="refIndex"
                  class="[referenceItem, clickableReference]"
                  @click="handleReferenceClick(refItem.id)"
                >
                  <span>{{ refItem.name }}</span>
                </li>
              </ul>
            </div>
            <div v-if="msg.sender === 'AI'" class="actions">
              <div class="rightActions">
                <CopyOutlined class="actionIcon" @click="handleCopyClick(msg.content)" />
              </div>
            </div>
          </div>
          <div v-if="isGenerating" class="messageItem" style="background-color: #ffffff; border-radius: 10px; padding: 10px; display: flex; align-items: center;">
            <div class="messageBody">
              <p style="color: #333; font-size: 14px; margin: 0; flex-grow: 1;">
                AI 正在生成回复...
              </p>
              <div class="loadingSpinner" />
            </div>
          </div>
        </div>
        <div class="recommendedQuestions">
          <button
            v-for="(question, qIndex) in messages[0].recommendedQuestions"
            :key="qIndex"
            class="recommendedQuestionButton"
            @click="handleRecommendedQuestionClick(question)"
          >
            {{ question }}
          </button>
        </div>
        <div class="inputBox">
          <textarea
            ref="inputElementRef"
            v-model="inputValue"
            placeholder="请输入你的问题"
            class="input"
            rows="1"
            @input="autoResizeTextarea"
          />
          <button class="sendButton" @click="handleSendClick">
            <img src="@/assets/652.png" alt="发送" class="sendIcon">
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.draggableContainer {
  position: absolute;
  z-index: 1000;
  cursor: pointer;
  // height: 37.5rem;
}

.iconContainer {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 7.5rem;
  height: 3.75rem;
  border-radius: 0.625rem;
  background-color: #ffffff;
  box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.15);
}

.aiIcon {
  width: 3.75rem;
  height: 2.5rem;
  // margin-left: -0.625rem;
  margin-top: 0.625rem;
  margin-right: 0.625rem;
}

.iconText {
  font-size: 1.25rem;
  color: #003399;
}

.chatContainer {
  width: 37.5rem;
  max-height: 62.5rem;
  border-radius: 0.5rem;
  background-color: #ffffff;
  padding: 1rem;
  display: flex;
  flex-direction: column;
}

.chatHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 0;
}

.headerContent {
  display: flex;
  align-items: center;
  font-size: 1.25rem;
  color: #003399;
}

.closeButton {
  border: none;
  background: none;
  font-size: 1.875rem;
  cursor: pointer;
}

.chatContent {
  flex: 1;
  overflow-y: auto;
  padding: 0.625rem 0;
}

.chatMessages {
  margin-top: 0;
  max-height: 25rem;
  overflow-y: auto;
  min-height: 25rem;
}

.messageItem {
  display: inline-block;
  margin-bottom: 1.875rem;
  padding: 0.125rem;
  background-color: #f5f6fd;
  border-radius: 0.5rem;
  position: relative;
  max-width: 100%;
}

.myMessage {
  background-color: #003399;
  color: #ffffff;
  float: right;
  text-align: left;
  margin-right: 0;
  margin-left: auto;
  display: inline-block;
}

.messageBody {
  margin-left: 0.625rem;
  font-size: 0.875rem;
  color: #ffffff;
}

.references {
  margin-left: 1.25rem;
  margin-top: 0.625rem;
  margin-right: 1.25rem;
}

.references p {
  margin: 0;
  font-weight: bold;
  color: #888;
}

.references ul {
  list-style: none;
  padding-left: 1.25rem;
}

.references li {
  position: relative;
  padding-left: 1.25rem;
  margin-bottom: 0.3125rem;
}

.referenceItem {
  color: #888;
  cursor: pointer;
}

.hoveredReference {
  position: absolute;
  background-color: black;
  color: #fff;
  padding: 0.3125rem 0.625rem;
  border-radius: 0.25rem;
  white-space: nowrap;
  z-index: 1000;
  transform: translateY(-100%);
}

.time {
  margin-left: 0.625rem;
  color: #003399;
}

.actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.625rem;
}

.leftActions {
  display: flex;
  gap: 0.625rem;
  margin-left: 1.25rem;
}

.rightActions {
  margin-left: auto;
  margin-right: 1.25rem;
}

.actionIcon {
  font-size: 1rem;
  color: #333;
  cursor: pointer;
}

.inspirationBox {
  margin-top: 0.5rem;
  display: flex;
  justify-content: center;
}

.inspirationButton {
  padding: 0.375rem 0.75rem;
  background-color: #ffffff;
  color: black;
  border: 1px solid #003399;
  border-radius: 0.625rem;
  cursor: pointer;
}

.inspirationIcon {
  margin-right: 0.375rem;
  font-size: 1rem;
  color: rgb(218, 218, 26);
}

.inputBox {
  display: flex;
  align-items: center;
  margin-top: 1rem;
  background-color: #ffffff;
  border-radius: 0.625rem;
  padding: 0.3125rem;
  border: 1px solid #003399;
}

.input {
  flex: 1;
  padding: 0.75rem;
  border-radius: 0.3125rem;
  border: none;
  resize: none;
  overflow: hidden;
  font-size: 1rem;
  outline: none;
}

.sendButton {
  padding: 0.625rem 0.25rem;
  background-color: #003399;
  color: #fff;
  border: none;
  border-radius: 0.75rem;
  cursor: pointer;
  margin-left: 0.5rem;
  height: 2.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sendIcon {
  width: 100%;
  max-width: 1.5625rem;
  max-height: 1.5625rem;
  height: auto;
}

.clickableReference {
  cursor: pointer;
  transition: color 0.2s ease-in-out;
}

.clickableReference:hover {
  color: #1677ff;
}

.recommendedQuestions {
  display: flex;
  justify-content: space-around;
  margin-top: 0.625rem;
  padding: 0.625rem 0;
  border-top: 1px solid #eaeaea;
}

.recommendedQuestionButton {
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 0.25rem;
  padding: 0.3125rem 0.625rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.recommendedQuestionButton:hover {
  background-color: #f0f0f0;
}

.loadingSpinner {
  border: 0.1875rem solid rgba(0, 0, 0, 0.1);
  border-left-color: #333;
  border-radius: 50%;
  width: 1.125rem;
  height: 1.125rem;
  animation: spin 0.8s linear infinite;
  margin-left: 0.625rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
